package com.gitee.srurl.core.factory.handle;

import com.gitee.srurl.core.annotation.Order;
import com.gitee.srurl.core.api.IDuplicateDetection;
import com.gitee.srurl.core.config.ShortUrlConfig;
import com.gitee.srurl.core.dto.request.GenerateShortUrlDTO;
import com.gitee.srurl.core.dto.request.UrlDuplicateCheckResultDTO;
import com.gitee.srurl.core.factory.ShortUrlFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author zxw
 * @date 2023/4/29 7:49
 */
@Slf4j
@Component
@Order(2)
public class DuplicateDetectionHandle implements IGenerateShortUrlHandle {

    @Override
    public boolean handle(GenerateShortUrlDTO generateShortUrlDTO) {

        // 每次生成都是新的url的话 不检测重复
        if (generateShortUrlDTO.getAlwaysNewUrl()) {
            return true;
        }

        ShortUrlConfig shortUrlConfig = ShortUrlFactory.getShortUrlConfig();
        IDuplicateDetection duplicateDetection = shortUrlConfig.getDuplicateDetection();
        String originUrl = generateShortUrlDTO.getOriginUrl();
        UrlDuplicateCheckResultDTO urlDuplicateCheckResultDTO = duplicateDetection.checkDuplicate(originUrl);
        if (urlDuplicateCheckResultDTO.isDuplicate()) {
            if (urlDuplicateCheckResultDTO.isDisabled()) {
                generateShortUrlDTO.setMsg("短链被禁用");
                generateShortUrlDTO.setSuccess(false);
                return false;
            }
            // 说明url重复，返回之前的url
            generateShortUrlDTO.setShortKey(urlDuplicateCheckResultDTO.getHistoryShortKey());
            generateShortUrlDTO.setShortUrl(urlDuplicateCheckResultDTO.getHistoryShortUrl());
            boolean renewalStatus = ShortUrlFactory.shortUrlRenewal(generateShortUrlDTO);
            if (!renewalStatus) {
                generateShortUrlDTO.setMsg("重复生成短url,续期失败");
                generateShortUrlDTO.setSuccess(false);
                return false;
            }
            generateShortUrlDTO.setSuccess(true);
            return false;
        }

        return true;
    }
}
